import { ref, watch } from 'vue'
import { defineStore } from 'pinia'

export const useThemeStore = defineStore('theme', () => {
  // 从 localStorage 读取主题设置，默认为暗色主题
  const theme = ref(localStorage.getItem('theme') || 'dark')

  // 应用主题到 document
  const applyTheme = (newTheme) => {
    document.documentElement.setAttribute('data-theme', newTheme)
  }

  // 切换主题
  const toggleTheme = () => {
    theme.value = theme.value === 'dark' ? 'light' : 'dark'
  }

  // 设置特定主题
  const setTheme = (newTheme) => {
    if (newTheme === 'dark' || newTheme === 'light') {
      theme.value = newTheme
    }
  }

  // 监听主题变化，保存到 localStorage 并应用
  watch(theme, (newTheme) => {
    localStorage.setItem('theme', newTheme)
    applyTheme(newTheme)
  }, { immediate: true })

  return {
    theme,
    toggleTheme,
    setTheme
  }
})
